package com.lapelittle.framework.controller;

import com.lapelittle.framework.common.Result;
import com.lapelittle.framework.model.UserUpdateRequest;
import com.lapelittle.framework.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;
import org.springframework.web.multipart.MultipartFile;
import java.util.Map;

@Tag(name = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Value("${file.upload.path}")
    private String uploadPath;

    @Operation(summary = "更新用户信息")
    @PostMapping("/update")
    public Result<String> updateUser(@RequestBody UserUpdateRequest request, HttpServletRequest httpRequest) {
        try {
            Long userId = (Long) httpRequest.getAttribute("userId");
            if (userService.updateUser(userId, request)) {
                return Result.ok("更新成功");
            }
            return Result.error("更新失败");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "上传头像")
    @PostMapping("/uploadAvatar")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            if (file.isEmpty()) {
                return Result.error("请选择文件");
            }
            
            // 创建上传目录
            String directory = uploadPath + "/avatar/";
            File dir = new File(directory);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            if(originalFilename == null){
                return Result.error("文件名不能为空");
            }
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + extension;
            String fullPath = directory + filename;
            
            // 使用transferTo方法保存文件
            File dest = new File(fullPath);
            file.transferTo(new File(dest.getAbsolutePath()));
            
            // 返回文件访问URL（使用相对路径）
            String fileUrl = "/upload/avatar/" + filename;
            return Result.ok(fileUrl);
        } catch (Exception e) {
            e.printStackTrace(); // 添加错误日志
            return Result.error("文件上传失败");
        }
    }

    @Operation(summary = "发送邮箱验证码")
    @PostMapping("/sendEmailCode")
    public Result<String> sendEmailCode(@RequestBody Map<String, String> params, HttpServletRequest request) {
        try {
            String email = params.get("email");
            Long userId = (Long) request.getAttribute("userId");
            userService.sendEmailCode(userId, email);
            return Result.ok("验证码已发送");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "验证邮箱验证码")
    @PostMapping("/verifyEmailCode")
    public Result<String> verifyEmailCode(@RequestBody Map<String, String> params, HttpServletRequest request) {
        try {
            String email = params.get("email");
            String code = params.get("code");
            Long userId = (Long) request.getAttribute("userId");
            if (userService.verifyEmailCode(userId, email, code)) {
                return Result.ok("验证成功");
            }
            return Result.error("验证码错误");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
} 